import json

import mitmproxy
from mitmproxy import http, ctx


class Events:

    def request(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP request has been read.
            可以在request请求中实现maplocal操作
        """
        """https://stock.xueqiu.com/v5/stock/batch/quote.json?_t=1NETEASEa0f55c1405c4ad96f2663d8754f5795a.5130872742.1640604941186.1640604946764&_s=9d373a&symbol=SH600519%2C01810%2CJD%2CSH601318%2CBABA&extend=detail"""
        # if "quote.json" in flow.request.pretty_url:
        #     with open("quote.json",encoding="utf-8") as f:
        #         flow.response = http.HTTPResponse.make(
        #             200,
        #             f.read(),
        #             {"content-type":"application/json;charset=UTF-8"},
        #         )
        pass


    def response(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP response has been read.
            实现rewrite
        """
        if "quote.json" in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            # data = json.loads(flow.response.content)
            # ctx.log.info(data)
            ctx.log.info(str(flow.response.content))
            data = json.loads(flow.response.content)
            with open("data.json","w",encoding="utf-8") as f:
                f.write(str(data))
            data['data']['items'][0]["quote"]["name"] = "hogwarts7"
            data['data']['items'][1]["quote"]["name"] = "hogwarts6666"
            data['data']['items'][2]["quote"]["percent"] = "-99.899"
            data['data']['items'][3]["quote"]["current"] = "999999.9999"
            flow.response.text = json.dumps(data)


addons = [
    Events()
]